﻿using System.Data;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using MongoDB.Driver.Builders;

namespace Yamfinder.Data
{
    public class DataDictonaryRepository : IDataDictonaryRepository
    {
        private readonly MongoCollection<DataDictonaryEntry> _collection;
        public const string CollectionName = "DataDic";

        public DataDictonaryRepository(IDataSource dataSource)
        {
            _collection = dataSource.GetCollection<DataDictonaryEntry>(CollectionName);
        }

        public IQueryable<DataDictonaryEntry> Query()
        {
            return _collection.AsQueryable();
        }

        public DataDictonaryEntry Get(ObjectId id)
        {
            return _collection.FindOneById(id);
        }

        public DataDictonaryEntry Get(string fieldName)
        {
            return _collection.FindOne(MatchFieldName(fieldName));
        }

        public void Insert(DataDictonaryEntry entry)
        {
            //Check for duplicates
            if (_collection.Find(MatchFieldName(entry.Name)).Count() > 0)
                throw new DataException("Duplicate Field Name, cannot continue.");

            _collection.Insert(entry);
        }

        public void Save(DataDictonaryEntry entry)
        {
            var origObject = Get(entry.Id);
            if (origObject.Name != entry.Name)
            {   
                //Check for duplicates
                if (_collection.Find(MatchFieldName(entry.Name)).Count() > 0)
                    throw new DataException("Duplicate Field name, cannot continue.");
            }

            _collection.Save(entry);
        }

        public void Remove(ObjectId id)
        {
            _collection.Remove(MatchId(id));
        }

        public void Remove(string fieldName)
        {
            _collection.Remove(MatchFieldName(fieldName));
        }

        private QueryComplete MatchId(ObjectId id)
        {
            return MongoDB.Driver.Builders.Query.EQ("_id", id);
        }

        private QueryComplete MatchFieldName(string fieldName)
        {
            return MongoDB.Driver.Builders.Query.EQ("Name", fieldName);
        }
    }
}